<template>
  <template v-for="route in routes" :key="route.path">
    <template v-if="!route.hidden">
      <!-- 有子路由的情况 -->
      <el-sub-menu
          v-if="route.children && route.children.length > 0 && hasVisibleChildren(route)"
          :index="resolvePath(route.path)"
      >
        <template #title>
          <el-icon :size="18">
            <component :is="route.meta.icon || 'Menu'" />
          </el-icon>
          <span>{{ route.meta.title }}</span>
        </template>

        <!-- 递归渲染更深层次的子菜单 -->
        <sidebar-menu-item
            :routes="route.children"
            :base-path="resolvePath(route.path)"
        />
      </el-sub-menu>

      <!-- 没有子路由的情况 -->
      <el-menu-item
          v-else
          :index="resolvePath(route.path)"
      >
        <template #title>
          <el-icon :size="18">
            <component :is="route.meta.icon || 'Menu'" />
          </el-icon>
          <span>{{ route.meta.title }}</span>
        </template>
      </el-menu-item>
    </template>
  </template>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
import { Menu } from '@element-plus/icons-vue'

const props = defineProps({
  routes: {
    type: Array,
    default: () => []
  },
  basePath: {
    type: String,
    default: ''
  }
})

const router = useRouter()

// 解析路由路径
const resolvePath = (path) => {
  if (path.startsWith('/')) return path
  return props.basePath ? `${props.basePath}/${path}` : `/${path}`
}

// 检查是否有可见的子路由
const hasVisibleChildren = (route) => {
  return route.children.some(child => !child.hidden)
}
</script>
